<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>A+管理</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="format-detection" content="telephone=no">
		<!-- jQuery-->
		<script type="text/javascript" src="/static/plugins/jquery/jquery-3.6.0.min.js"></script>

		<!-- layui-->
		<link rel="stylesheet" href="/static/plugins/layui/2.7.6/css/layui.css" media="all">
		<script src="/static/plugins/layui/2.7.6/layui.js" charset="utf-8"></script>

		<!-- common -->
		<link rel="stylesheet" href="/static/admin/css/common.css" media="all" />
		<link rel="stylesheet" href="/static/admin/css/mini-ease.css" media="all" />
		
		
	</head>

	
	<body>

	<!-- 列表 -->
	<div class="layui-row layui-col-space5" style="width:90%;margin: 0 auto;">

		<div class="layui-col-md12" id="id_panel_left_grid">
			<div class="layui-panel" style="overflow: auto; padding-top: 0.2rem;">
				<div class="mid-content">

					<table class="layui-hide" id="main_table" lay-filter="main_table"></table>

					<script type="text/html" id="toolbarDemo">
						<div class="layui-row" style="height: 40px;" id="toolbarDemoBtn">
							<div class="layui-col-xs12">
								<button type="button" class="layui-btn layui-bg-blue layui-btn-sm"  lay-on="add-data" id="addBtn">
									<i class="layui-icon layui-icon-add-1 layui-font-12"></i> 新增
								</button>
								<button type="button" class="layui-btn layui-bg layui-btn-sm"  lay-on="save-data">
									<i class="layui-icon layui-icon-ok-circle layui-font-12"></i> 保存
								</button>
								<button type="button" class="layui-btn layui-bg-blue layui-btn-sm"  lay-on="export-data">
									<i class="layui-icon layui-icon-release layui-font-12"></i> 导出
								</button>
                                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm"  lay-event="del-data" lay-on="del-data">
                                    <i class="layui-icon layui-icon-delete layui-font-12"></i> 删除
                                </button>
							</div>

						</div>
					</script>
					<script type="text/html" id="templet_index_no">{{d.LAY_TABLE_INDEX+1}}</script>
				</div>
			</div>
		</div>
	</div>


	<input type="hidden" name="boutiqueId" id="boutiqueId" value=""><!--精品库Id-->
	<input type="hidden" name="code" id="code" value=""><!--商品编码-->
	<input type="hidden" name="boutiqueSiteDetailId" id="boutiqueSiteDetailId" value=""><!--精品库站点信息表Id-->

      <script>
		  $('#boutiqueId').val('[(${dto.boutiqueId})]');
		  $('#code').val('[(${dto.code})]');
		  $('#boutiqueSiteDetailId').val('[(${dto.boutiqueSiteDetailId})]');
		  var onProcess = [[${onProcess}]];

		  var newId = 0;//新增数据临时Id
		  var dataList = [];

		  //获取列表数据
		  $.ajax({
			  url : (onProcess=='0'?'/api/inter/tpAplusFile/searchByBoutiqueSiteDetailId':'/api/inter/tpAplusFile/searchByBoutiqueSiteDetailIdByAuth'),
			  data : {id:$('#boutiqueSiteDetailId').val()},
			  type : 'POST',
			  async : false,//关闭异步
			  success : function(result) {
				  if (result.code == '0') {
					  dataList = result.data;
				  }else{
					  layer.msg(result.msg);
				  }
			  }
		  });
		  layui.config({
				//自定义layui组件的目录,设定扩展的layui模块的所在目录，一般用于外部模块扩展
				base: '/static/js/layui_extends/'
			}).use(['form', 'element', 'table', 'dropdown', 'util', 'laydate', 'upload', 'YsModal'], function(){
					  var element = layui.element;
					  var table = layui.table;
					  var dropdown = layui.dropdown;
					  var form = layui.form;
					  var util = layui.util;
					  var $ = layui.jquery;
					  var laydate = layui.laydate;
					  var upload = layui.upload;
			  		  var cols =[];

			  		  if(onProcess=='0'){
						  cols =[ //表头
							  [
                                  {title: '', type: 'checkbox',  unresize: true, width: '40'},
								  {title: '序号',   align:"center",type:"numbers"},
								  {title: '公司编码',   width: '120' , field:'vgsBm' ,align:"center",
									  templet: function(d){
										  return '<div class="layui-table-link" onclick="chooseModel('+ d.id + ')" style="cursor: pointer;"  title="选择公司">' +
												  '<div style="float:left;width: 82%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">' + (d.vgsBm==undefined?'':d.vgsBm) + '   </div>' +
												  '<div style="float:right;width: 17%;" >' +
												  '<i class="layui-icon layui-icon-more" style="float: right;" ></i>' +
												  '</div>' +
												  '</div>';
									  }

								  },
								  {title: '公司简称',   width: '120' , field:'vgsJc' ,align:"center"},
								  {title: '文件名称', width: '200' , field:'fileName', align:"center",
									  templet: function(d){
										  return '<div class="layui-table-link upload_files" id="'+ d.id + '" style="cursor: pointer;" >' +
												  '<div style="float:left;width: 82%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">' + (d.fileName==undefined?'':d.fileName) + '   </div>' +
												  '<div style="float:right;width: 17%;"  title="点击上传">' +
												  '<i class="layui-icon layui-icon-upload" style="float: right;" ></i>' +
												  '</div>' +
												  '</div>';
									  }
								  },
								  {title: '文件大小', width: '100' , field:'fileSize', align:"center"},
								  {title: '单位', width: '100' , field:'fileSizeUnit', align:"center"},
								  {title: '文件类型', width: '100' , field:'fileType', align:"center"},
								  {title: '上传时间', width: '150' , field:'updateTime', align:"center",
									  templet: function(d){
										  return '<div>' + (d.updateTime==undefined?'':setTimeStr(d.updateTime)) + '   </div>';
									  }

								  },
								  {title: '操作', width: '240' , align:"center",templet:
											  function(d){
												  var str = '';
												  if(d.fileName!=undefined && d.fileName!=null){
													  str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="toOpenFile(\''+d.id+'\');"><i class="layui-icon layui-icon-search layui-font-12"></i> 查看</button>';
													  str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="toDownload(\''+d.id+'\');"><i class="layui-icon layui-icon-download-circle layui-font-12"></i> 下载</button>';
												  }
												  //str +='<button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="toDel(\''+d.id+'\');"><i class="layui-icon layui-icon-delete layui-font-12"></i> 删除</button>';
												  return str;
											  }
								  },
							  ]
						  ];
					  }else {//不可编辑
						  cols =[ //表头
							  [
                                  {title: '', type: 'checkbox',  unresize: true, width: '40'},
								  {title: '序号',   align:"center",type:"numbers"},
								  {title: '公司编码',   width: '120' , field:'vgsBm' ,align:"center"},
								  {title: '公司简称',   width: '120' , field:'vgsJc' ,align:"center"},
								  {title: '文件名称', width: '200' , field:'fileName', align:"center"},
								  {title: '文件大小', width: '100' , field:'fileSize', align:"center"},
								  {title: '单位', width: '100' , field:'fileSizeUnit', align:"center"},
								  {title: '文件类型', width: '100' , field:'fileType', align:"center"},
								  {title: '上传时间', width: '150' , field:'updateTime', align:"center",
									  templet: function(d){
										  return '<div>' + (d.updateTime==undefined?'':setTimeStr(d.updateTime)) + '   </div>';
									  }

								  },
                                  {title: '操作', width: '240' , align:"center",templet:
                                          function(d){
                                              var str = '';
                                              if(d.fileName!=undefined && d.fileName!=null){
                                                  str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="toOpenFile(\''+d.id+'\');"><i class="layui-icon layui-icon-search layui-font-12"></i> 查看</button>';
                                                  str += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="toDownload(\''+d.id+'\');"><i class="layui-icon layui-icon-download-circle layui-font-12"></i> 下载</button>';
                                              }
                                              return str;
                                          }
                                  },
							  ]
						  ];
					  }
					  // 创建渲染实例
					  table.render({
						  id:'main_table'
						  ,elem: '#main_table'
						  //,url:'/api/inter/knowledgeType/searchType' // 此处为静态模拟数据，实际使用时需换成真实接口
						  ,data:dataList
						  ,toolbar: (onProcess=='0'?'#toolbarDemo':'')
						  ,defaultToolbar: [ 'filter',{
							  title: '刷新页面'
							  ,layEvent: 'LAYTABLE_REFRESH'
							  ,icon: 'layui-icon-refresh'
						  }]
						  ,height: window.innerHeight - 70 // 最大高度减去其他容器已占有的高度差
						  ,where: {id:'[(${dto.boutiqueSiteDetailId})]'}
						  ,cellMinWidth: 95
						  ,limit : 20
						  ,limits : [20,50,200,500]
						  ,page: true
						  ,request: {
							  pageName: 'page',
							  limitName: 'size'
						  }
						  //,skin: 'row'
						  ,even: false // 开启隔行背景
						  ,skin: 'grid'//设置表格边框风格
						  ,cols:cols
						  ,done: function(res){
							  setUpload();
						  }
						  ,error: function(res, msg){
							  console.log(res, msg)
						  }
					  });


					  // 工具栏事件
					  table.on('toolbar(main_table)', function(obj){
						  var id = obj.config.id;
						  var checkStatus = table.checkStatus(id);
                          var datas = checkStatus.data;
						  var othis = lay(this);
						  switch(obj.event){
                              case 'LAYTABLE_REFRESH':
							  {
								  layer.confirm("确定刷新吗？",{
									  btn: ['确定', '取消']
								  }, function (index) {
									  location.reload();
									  layer.close(index);
								  });
								  break;
							  }
                              case 'del-data'://删除
                              {
                                  if(datas.length == 0) {
                                      layer.alert('尚未选中数据');
                                  }else {
                                      var oldId = [];
                                      for(var j=0;j<datas.length;j++){
                                          if(datas[j].id<=0){//若是新增的，还未保存，直接删除
                                              var dataListNew = [];
                                              for(var i=0;i<dataList.length;i++){
                                                  if(dataList[i].id!=datas[j].id){
                                                      dataListNew.push(dataList[i]);
                                                  }
                                              }
                                              dataList = dataListNew;
                                              //$('#addBtn').show();
                                          }else {
                                              oldId = [datas[j].id];
                                          }
                                      }
                                      if(oldId!=null && oldId.length>0){
                                          delYes(oldId);
                                      }else{
                                          //刷新表单
                                          layui.table.reloadData('main_table', { data: dataList});
                                      }


                                  }


                              }
						  };
					  });

					  // 普通事件
					  util.on('lay-on', {
						  //新增
						  "add-data": function(){
							  dataList.push({
								  id:newId,
								  //fileName:""
							  });
							  table.reloadData('main_table', { data: dataList});
							  newId--;
						  },
						  //保存
						  "save-data": function(){
							  toAdd();
						  },
						  //导出
						  "export-data":function () {
							  $.ajax({
								  type: "POST",
								  url: '/api/inter/tpAplusFile/export',
								  data: {id:$('#boutiqueSiteDetailId').val()},
								  success: function (data) {
									  if (data.code == 0) {
										  if(data.msg != undefined && data.msg.startsWith('http')) {
											  window.open(data.msg);
										  } else {
											  layer.msg(data.msg);
										  }
									  } else {
										  alert(data.msg);
									  }
								  }
							  });
						  },


					  })

				  });



		  //弹出层
		  	function chooseModel(id) {
		  		// 打开单选框
				layui.YsModal.init({modalKey: 'THR_OperateCompanyApply', colCode: id, parentObj: window,extraData:id})
			  
				//return;

			}
		  //弹出层回调
		  function matchValuesAfterModalSelectRadio(colCode, data,extraData) {
			  if (data == "none" || !data) {//没有选中时
				  layer.msg("请选择！", {icon: 7});
			  } else {
				  var dataListNew = [];
				  for(var i=0;i<dataList.length;i++){
					  if(dataList[i].id==colCode){
						  dataList[i].vgsBm = data.vGsBm;
						  dataList[i].vgsJc = data.vGsJc;
					  }
					  dataListNew.push(dataList[i]);
				  }
				  dataList = dataListNew;

				  //layer.close(index);
				  layui.table.reloadData('main_table', { data: dataList});
			  }
		  }
			//上传文件控件初始化
		  function setUpload() {
			  layui.upload.render({
				  //elem: '#upload_files_'+id,
				  elem: '.upload_files',
				  url: 'https://file.mini-ease.com/api/outer/upload/uploadForERP_1_0',
				  multiple: false,
				  accept: 'file',
				  auto:true,
				  done: function(res){
					  var item = this.item;
					  var id = item[0].id;
					  //console.log("上传返回res",res);
					  var dataListNew = [];
					  for(var i=0;i<dataList.length;i++){
						  if(dataList[i].id==id){
							  dataList[i].fileName = res.data.fileName;
							  dataList[i].filePath = res.data.filePath;
							  dataList[i].fileSize = res.data.fileSize;
							  dataList[i].fileSizeUnit = res.data.fileSizeUnit;
							  dataList[i].fileType = res.data.fileType;
						  }
						  dataListNew.push(dataList[i]);
					  }
					  dataList = dataListNew;
					  //console.log('dataList',dataList);
					  //刷新列表
					  layui.table.reloadData('main_table', { data: dataList});
				  },
			  });
		  }


		  //转时间格式
		  function setTimeStr(timestamp) {
			  var date = new Date(timestamp);
			  var year = date.getFullYear();
			  var month = ('0' + (date.getMonth() + 1)).slice(-2);
			  var day = ('0' + date.getDate()).slice(-2);
			  var hours = ('0' + date.getHours()).slice(-2);
			  var minutes = ('0' + date.getMinutes()).slice(-2);
			  var seconds = ('0' + date.getSeconds()).slice(-2);
			  var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
			  return formattedDate;
		  }

		  //打开文件
		  function toOpenFile(id) {
			 var filePath = '';
			  for(var i=0;i<dataList.length;i++){
				  if(dataList[i].id==id){
					  filePath = dataList[i].filePath;
				  }
			  }
			  window.open(filePath);
		  }

		  //下载文件
		  function toDownload(id) {
			  var data = {};
			  for(var i=0;i<dataList.length;i++){
				  if(dataList[i].id==id){
					  data = dataList[i];
				  }
			  }
			  fetch(data.filePath).then(res => res.blob().then(blob => {
				  let a = document.createElement('a');
				  let url = window.URL.createObjectURL(blob);
				  a.href = url;
				  a.download = data.fileName ;//+ '.' + data.fileType;
				  a.click();
				  window.URL.revokeObjectURL(url);
			  }))
		  }

		  //删除
		  function toDel(id) {

			  if(id<=0){//若是新增的，还未保存，直接删除
			  	var dataListNew = [];
			  	for(var i=0;i<dataList.length;i++){
			  		if(dataList[i].id!=id){
						dataListNew.push(dataList[i]);
					}
				}
				  dataList = dataListNew;
				  $('#addBtn').show();
				  layui.table.reloadData('main_table', { data: dataList});
			  }else {
				  layer.confirm('确定要删除该A+附件?', {icon: 3}, function () {
					  //点击确定的回调
					  layui.layer.msg('请稍后', {
						  icon: 16,
						  shade: 0.01
					  });
					  delYes(id);
				  }, function () {});//点击取消的回调
			  }
		  }


		  //确定删除
		  function delYes(ids){
			  $.ajax({
				  url: '/api/inter/tpAplusFile/del',
                  data: "list="+ids,
                  /*
				  data: { 'id':id },
                   */
				  type: 'POST',
				  async: true,
				  success: function (result) {
					  if(result.code=='0'){
						  layer.close();
						  layer.msg("操作成功", {icon: 1});
						  var dataListNew = [];
                          for(var i=0;i<dataList.length;i++){
                              var isdel = false;
                              for(var j=0;j<ids.length;j++){
                                  if(dataList[i].id==ids[j]){
                                      isdel = true;
                                  }
                              }
                              if(!isdel){
                                  dataListNew.push(dataList[i]);
                              }
                          }
						  dataList = dataListNew;
						  layui.table.reloadData('main_table', { data: dataList});
					  }else {//失败
						  layer.close();
						  layer.msg("删除失败，请稍后再试！", {icon: 2});
					  }
				  },
				  error: function () {
					  layer.close();
					  layer.msg("删除失败，请稍后再试！", {icon: 2});
				  }
			  });
		  }

		  //新增保存
		  function toAdd() {
		  		if(dataList==null || dataList.length<=0){
					layer.msg('请新增数据！', {icon: 0});
					return ;
				}

			  var errorMsg = null;
			  for(var i=0;i<dataList.length;i++){
				  if(dataList[i].vgsBm ==undefined || dataList[i].vgsBm ==null || dataList[i].vgsBm =='' ){
					  errorMsg = '第'+(i+1)+'行数据，公司编码为空！';
				  }
				  if(dataList[i].vgsJc ==undefined || dataList[i].vgsJc ==null || dataList[i].vgsJc =='' ){
					  errorMsg = '第'+(i+1)+'行数据，公司简称为空！';
				  }
				  if(dataList[i].fileName ==undefined || dataList[i].fileName ==null || dataList[i].fileName =='' ){
					  errorMsg = '第'+(i+1)+'行数据，文件名称为空！';
				  }
				  if(dataList[i].fileSize ==undefined || dataList[i].fileSize ==null || dataList[i].fileSize =='' ){
					  errorMsg = '第'+(i+1)+'行数据，文件大小为空！';
				  }
				  if(dataList[i].fileSizeUnit ==undefined || dataList[i].fileSizeUnit ==null || dataList[i].fileSizeUnit =='' ){
					  errorMsg = '第'+(i+1)+'行数据，单位为空！';
				  }
				  if(dataList[i].fileType ==undefined || dataList[i].fileType ==null || dataList[i].fileType =='' ){
					  errorMsg = '第'+(i+1)+'行数据，文件类型为空！';
				  }
			  }
			  if(errorMsg!=null){
				  layer.msg(errorMsg, {icon: 0});
				  return ;
			  }
			  var layindex= layer.load(2);
			  $.ajax({
				  url: '/api/inter/tpAplusFile/toAddOrUpdateByList',
				  data: {
					  'boutiqueId':$('#boutiqueId').val(),//精品库Id
					  'code':$('#code').val(),//商品编码
					  'boutiqueSiteDetailId':$('#boutiqueSiteDetailId').val(),//精品库站点信息表Id
					  'dataList': JSON.stringify(dataList) //参数list
				  },
				  type: 'POST',
				  async: true,
				  success: function (result) {
					  layer.close(layindex);
					  console.log('保存返回result:',result);
					  if(result.code=='0'){
						  layer.msg("操作成功", {icon: 1});
						  parent.window.$('#aPlusCount').text("("+dataList.length+"个附件)");
						  //关闭页面
						  setTimeout(function(){
							  parent.window.layer.closeAll();
						  }, 1000);

					  } else if (result.code == 1) {//失败
						  layer.msg(result.msg, {icon: 2});
					  }else{//失败
						  layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
					  }
				  },
				  error: function () {
					  layer.close(layindex);
					  layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
				  }
			  });
		  }



      </script>

  </body>
</html>